package io.jee.runshan.service.remote.qiye.impl;

import io.jee.medusa.remote.RemoteConnector;
import io.jee.runshan.domain.remote.qiye.DepartmentCreate;
import io.jee.runshan.domain.remote.qiye.DepartmentList;
import io.jee.runshan.domain.remote.qiye.UserDetail;
import io.jee.runshan.domain.remote.qiye.UserInvite;
import io.jee.runshan.domain.remote.qiye.UserList;
import io.jee.runshan.domain.remote.qiye.base.Response;
import io.jee.runshan.domain.remote.qiye.request.DepartmentData;
import io.jee.runshan.domain.remote.qiye.request.UserBatchdeleteData;
import io.jee.runshan.domain.remote.qiye.request.UserCreateData;
import io.jee.runshan.domain.remote.qiye.request.UserInviteData;
import io.jee.runshan.domain.remote.qiye.response.DepartmentListData;
import io.jee.runshan.service.remote.qiye.IUserService;
import io.jee.runshan.utils.FileTool;
import io.jee.runshan.utils.JsonUtil;
import io.jee.runshan.utils.QiyeConstant;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

@Component
public class UserServiceImpl implements IUserService {

	@Override
	public Response create(UserCreateData data) {
		String access_token = QiyeConstant.getApptoken();
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=" + access_token;
		String params = JsonUtil.beanToJson(data);
		return RemoteConnector.post(url, params, Response.class);
	}
	
	@Override
	public Response update(UserCreateData data) {
		String access_token = QiyeConstant.getApptoken();
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=" + access_token;
		String params = JsonUtil.beanToJson(data);
		return RemoteConnector.post(url, params, Response.class);
	}
	
	@Override
	public Response delete(String userId) {
		String access_token = QiyeConstant.getApptoken();
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=" + access_token + "&userid=" + userId;
		return RemoteConnector.get(url, null, Response.class);
	}
	
	@Override
	public Response batchdelete(UserBatchdeleteData ids) {
		String access_token = QiyeConstant.getApptoken();
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=" + access_token;
		String params = JsonUtil.beanToJson(ids);
		return RemoteConnector.post(url, params, Response.class);
	}

	@Override
	public UserDetail detail(String userId) {
		String access_token = QiyeConstant.getApptoken();
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + access_token + "&userid=" + userId;
		return RemoteConnector.get(url, null, UserDetail.class);
	}
	
	@Override
	public UserInvite invite(UserInviteData data) {
		String access_token = QiyeConstant.getApptoken();
		String url = "https://qyapi.weixin.qq.com/cgi-bin/invite/send?access_token=" + access_token;
		String params = JsonUtil.beanToJson(data);
		return RemoteConnector.post(url, params, UserInvite.class);
	}
	
	@Override
	public UserList list(Integer department_id, Integer fetch_child, Integer status) {
		String access_token = QiyeConstant.getApptoken();
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=" + access_token + "&department_id=" + department_id + "&fetch_child=" + fetch_child + "&status=" + status;
		return RemoteConnector.get(url, null, UserList.class);
	}

	@Override
	public Map<Object,Object> importUser(String tempPath) {
		Map<Object,Object> map = new HashMap<Object,Object>();
		Response response = null;
		try {
			Workbook wb = null;  
			if (tempPath.endsWith(".xls")) {  
	            wb = new HSSFWorkbook(new FileInputStream(tempPath));  
	        } else if (tempPath.endsWith(".xlsx")) {  
	            wb = new XSSFWorkbook(new FileInputStream(tempPath));  
	        }
	        
	        Sheet sheet1 = wb.getSheetAt(0);
	        boolean hasTitle = true;
	        String msg = "";
	        for (Row row : sheet1) {
	        	String msgs = null;
	        	if(hasTitle){
	        		hasTitle = false;
	        		continue;
	        	}
	        	int rowNum = row.getRowNum() + 1;
	        	String name = null;
	        	String userid = null;
	        	String weixinid = null;
	        	String mobile = null;
	        	String email = null;
	        	String department = null;
	        	String position = null;
	        	try {
	        		row.getCell(0).setCellType(HSSFCell.CELL_TYPE_STRING);
	        		name = row.getCell(0)==null?null:row.getCell(0).getStringCellValue();
				} catch (Exception e) {
					e.printStackTrace();
					msgs = "第" + rowNum + "行：获取姓名有误，请检查数据格式是否符合规范";
					msg += msgs + "<br>";
					continue;
				}
	        	try {
	        		row.getCell(1).setCellType(HSSFCell.CELL_TYPE_STRING);
	        		userid = row.getCell(1)==null?null:row.getCell(1).getStringCellValue();
				} catch (Exception e) {
					e.printStackTrace();
					msgs = "第" + rowNum + "行：获取帐号有误，请检查数据格式是否符合规范";
					msg += msgs + "<br>";
					continue;
				}
	        	try {
	        		row.getCell(2).setCellType(HSSFCell.CELL_TYPE_STRING);
	        		weixinid = row.getCell(2)==null?null:row.getCell(2).getStringCellValue();
				} catch (Exception e) {
					e.printStackTrace();
					msgs = "第" + rowNum + "行：获取微信号有误，请检查数据格式是否符合规范";
					msg += msgs + "<br>";
					continue;
				}
	        	try {
	        		row.getCell(3).setCellType(HSSFCell.CELL_TYPE_STRING);
	        		mobile = row.getCell(3)==null?null:row.getCell(3).getStringCellValue();
				} catch (Exception e) {
					e.printStackTrace();
					msgs = "第" + rowNum + "行：获取手机号有误，请检查数据格式是否符合规范";
					msg += msgs + "<br>";
					continue;
				}
	        	try {
	        		row.getCell(4).setCellType(HSSFCell.CELL_TYPE_STRING);
	        		email = row.getCell(4)==null?null:row.getCell(4).getStringCellValue();
				} catch (Exception e) {
					e.printStackTrace();
					msgs = "第" + rowNum + "行：获取邮箱有误，请检查数据格式是否符合规范";
					msg += msgs + "<br>";
					continue;
				}
	        	try {
	        		row.getCell(5).setCellType(HSSFCell.CELL_TYPE_STRING);
	        		department = row.getCell(5)==null?null:row.getCell(5).getStringCellValue();
				} catch (Exception e) {
					e.printStackTrace();
					msgs = "第" + rowNum + "行：获取所在部门有误，请检查数据格式是否符合规范";
					msg += msgs + "<br>";
					continue;
				}
	        	try {
	        		row.getCell(6).setCellType(HSSFCell.CELL_TYPE_STRING);
		        	position = row.getCell(6)==null?null:row.getCell(6).getStringCellValue();
				} catch (Exception e) {
					e.printStackTrace();
					msgs = "第" + rowNum + "行：获取职位有误，请检查数据格式是否符合规范";
					msg += msgs + "<br>";
					continue;
				}
	        	
	        	UserCreateData user = new UserCreateData();
	        	user.setName(name == null ? null : name.trim());
	        	user.setUserid(userid == null ? null : userid.trim());
	        	user.setWeixinid(weixinid == null ? null : weixinid.trim());
	        	user.setMobile(mobile == null ? null : mobile.trim());
	        	user.setEmail(email == null ? null : email.trim());
	        	user.setDepartment(getDeptIds(department == null ? null : department.trim()));
	        	user.setPosition(position == null ? null : position.trim());
	        	
	        	response = create(user);
	        	
	        	if(!response.success()){
	        		msgs = "第" + rowNum + "行：" + response.getErrmsg();
	        		msg += msgs + "<br>";
	        	}else{
	        		msgs = "第" + rowNum + "行：" + name + "（" + userid + "）" + "导入成功";
	        		msg += msgs + "<br>";
	        	}
	        }
	        map.put("msg", msg);
			map.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "读取文档错误，请检查文档是否符合规范");
			map.put("success", false);
		} finally {
			try {
				FileTool.deletefile(tempPath);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;
	}
	
	/**
	 * 获取部门id，没有则添加
	 * @param uploadText 
	 * 格式如下：
	 * "研发中心/产品开发部/研发部子一级/研发部子二级;销售中心/销售一部/国内市场部"
	 * @return
	 */
	public Integer[] getDeptIds(String uploadText) {
		String[] splitText = uploadText.split(";");
		Integer[] ids = new Integer[splitText.length];
		List<DepartmentListData> list = listDept().getDepartment();
		for (int i = 0; i < splitText.length; i++) {
			Integer id = null;
			Integer parentid = 1;
			String[] textName = splitText[i].split("/");
			for (int j = 0; j < textName.length; j++) {
				List<DepartmentListData> pidDept = new ArrayList<DepartmentListData>();
				for (DepartmentListData dept : list) {
					if(parentid == dept.getParentid() ){
						pidDept.add(dept);
					}
				}
				boolean bool = false;
				for (DepartmentListData dept : pidDept) {
					id = dept.getId();
					if(dept.getName().equals(textName[j])){
						bool = true;
						break;
					}
				}
				if(!bool){
					DepartmentData dd = new DepartmentData();
					dd.setName(textName[j]);
					dd.setParentid(parentid);
					DepartmentCreate dc = createDept(dd);
					id = dc.getId();
					list = listDept().getDepartment();
				}
				parentid = id;
			}
			ids[i] = id;
		}
		return ids;
	}
	
	public DepartmentList listDept() {
		String access_token = QiyeConstant.getApptoken();
		String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + access_token + "&id=1";
		return RemoteConnector.post(url, null, DepartmentList.class);
	}
	
	public DepartmentCreate createDept(DepartmentData data) {
		String access_token = QiyeConstant.getApptoken();
		String url = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=" + access_token;
		String params = JsonUtil.beanToJson(data);
		return RemoteConnector.post(url, params, DepartmentCreate.class);
	}
}
